#!/usr/bin/python

import socket
import struct
import string
import sys

# sinalizacao
# ABIT = 8 : ativo off-hook, desativo on-hook
# BBIT = 4 : desativo ringando, ativo sem ring
# CBIT = 2 : desativo
# DBIT = 1 : ativo

audioorig = open('601.raw','r').read()
posaudioorig = 0
audioenv=''
audio1 = []

def imprimepacote(pac):
   print " "
   # tira ethernet
   pac = pac[14:]
   print "Subaddr: %d" % struct.unpack('>H', pac[0:2])
   sampleschunk = struct.unpack('B', pac[2])[0]
   print "Samples Chunk: %d" % sampleschunk
   print "Flag: %d" % struct.unpack('B', pac[3])
   print "Counter: %d" % struct.unpack('>H', pac[4:6])
   canais = struct.unpack('>H', pac[6:8])[0]
   print "Number channels: %d" % canais
   tamsinaisbyte = (canais+1)/2
   bitssinais = pac[8:8+tamsinaisbyte]
   print "%02X"*tamsinaisbyte % struct.unpack('%dB' % tamsinaisbyte, bitssinais)
   samples = pac[8+tamsinaisbyte:]
   print ("%02X"*sampleschunk+" ")*canais % struct.unpack('%dB' % len(samples), samples)

s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0xd00d))
s.bind(("sn1", 0xd00d))

conta = 0
passo = 0
contapasso = 0
contapassoref = 2000
sinal = chr(0x55)*4
while passo < 14:
   pac = s.recv(1024)
   audio1.append(pac[34:42])
   conta += 1
   if conta > 500:
      conta = 0
      imprimepacote(pac)
   if 1:
      contapasso += 1
      if contapasso > contapassoref:
	 contapasso = 0
	 passo += 1
	 if passo ==  1: sinal = chr(0x55)+chr(0x5D)+chr(0x55)+chr(0x55)
	 if 0:
	    if passo ==  2: sinal = chr(0x55)+chr(0xD5)+chr(0x55)+chr(0x55)
	    if passo ==  3: sinal = chr(0x5D)+chr(0x55)+chr(0x55)+chr(0x55)
	    if passo ==  4: sinal = chr(0xD5)+chr(0x55)+chr(0x55)+chr(0x55)
	    if passo ==  5: sinal = chr(0x55)+chr(0x55)+chr(0x55)+chr(0x5D)
	    if passo ==  6: sinal = chr(0x55)+chr(0x55)+chr(0x55)+chr(0xD5)
	    if passo ==  7: sinal = chr(0x55)+chr(0x55)+chr(0x5D)+chr(0x55)
	    if passo ==  8: sinal = chr(0x55)+chr(0x55)+chr(0xD5)+chr(0x55)
	 if passo == 13: sinal = chr(0x55)+chr(0x55)+chr(0x55)+chr(0x55)
   if passo >= 2:
      audioenv = audioorig[posaudioorig:posaudioorig+8]
      posaudioorig += 8
   audioenv = audioenv+chr(0x7f)*(8-len(audioenv))
   pac = pac[6:11]+'0'+pac[0:5]+'1'+pac[12:22]+sinal+pac[26:34]+audioenv+pac[42:]
   s.send(pac)
open('saida.ulaw','w').write(string.join(audio1,''))
